package com.smart.home.netty;

import com.smart.home.util.CommandEncoder;
import com.smart.home.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Administrator
 * @version 1.0
 * @date 2017-03-09
 */
public class SendMessageHandler extends SimpleChannelInboundHandler<ByteBuf> {
    /**
     * 设备操作码，该操作码为16进制编码
     */
    private String command;

    public SendMessageHandler(String command) {
        this.command = command;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //连接成功，发送信息
        byte[] decode = CommandEncoder.decode(command);//编码处理
        ctx.writeAndFlush(Unpooled.copiedBuffer(decode));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        //接收返回数据
        String s = ByteBufUtil.hexDump(msg); //获取16进制数据
        System.out.println(s);
        //拆分数据结构后对局部数据进行解码
        //String buttonName = StringUtils.hexToStringGBK("d4b6b3ccc1acbdd3b2e2cad4");
        //System.out.println(buttonName);
        //返回数据包含各种数据的集合，需要分开解码
        /*if (msg.isReadable()) {
            System.out.println(msg.toString(Charset.forName("GBK")));//解码
        } else {
            System.out.println("没有接收到返回数据");
        }*/
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }


}
